package vip.liux.backend.adapter.webflux;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/api/ai/chat")
public class AiChatController {

    private final ChatClient chatClient;
    private final ChatMemory inMemoryChatMemory;
    private final HttpServletRequest servletRequest;

    public AiChatController(ChatClient chatClient, ChatMemory chatMemory, HttpServletRequest servletRequest) {
        this.chatClient = chatClient;
        this.inMemoryChatMemory = chatMemory;
        this.servletRequest = servletRequest;
    }

    @PostMapping(value = "/conversations", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChat(@RequestBody ChatRequest request) {
        //用户id
        String userId = servletRequest.getRemoteAddr();

        return chatClient.prompt(request.message())
                .advisors(new MessageChatMemoryAdvisor(inMemoryChatMemory, userId, 10), new SimpleLoggerAdvisor())
                .stream().content().map(content -> ServerSentEvent.builder(content).event("message").build())
                // 问题回答结速标识,以便前端消息展示处理
                .concatWithValues(ServerSentEvent.builder("[DONE]").build())
                .onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " + e.getMessage()).event("error").build()));
    }

    @GetMapping("/conversations")
    public Flux<Message> conversation(@RequestParam(value = "lastN", required = false, defaultValue = "10") Integer lastN) {
        //用户id
        String userId = servletRequest.getRemoteAddr();
        return Flux.fromIterable(inMemoryChatMemory.get(userId, lastN));
    }

    public record ChatRequest(String message) {

    }
}
